import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  RadioChangeEvent,
  message,
} from 'antd'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useNavigate, useParams } from 'react-router-dom'
import styles from './index.module.scss'
import Channel from '@/components/channel'
import { useEffect, useRef, useState } from 'react'
import type { UploadChangeParam } from 'antd/es/upload'
import type { UploadFile, UploadProps } from 'antd/es/upload/interface'
import { publishArticle, eidArticle } from '@/store/actions/publish'
import { useDispatch } from 'react-redux'
import type { AppDispatch } from '@/store'
import { http } from '@/utils/http'
export type Cover = {
  type: string
  images: string[]
}
export interface Article {
  id?: string
  title: string
  content: string
  type?: string
  channel_id: number
  cover?: Cover
}
interface Res {
  data: {
    data: Article
    message: string
  }
}
const Publish = () => {
  const dispatch = useDispatch<AppDispatch>()
  const navigate = useNavigate()
  const params = useParams()
  // 上传图片列表格式=》 [{url:'}...]
  const [fileList, setFileList] = useState<any[]>([])
  // 控制图片上传数量：1 0 3
  const [count, setCount] = useState<number>(1)
  // 获取表单实例对象
  const [form] = Form.useForm()
  const fileArr = useRef<any[]>([])
  const id = params['*']
  useEffect(() => {
    const getArticleList = async (id: string) => {
      try {
        console.log('is1')
        // 获取文章信息
        const res: Res = await http.get(`/mp/articles/${id}`)
        console.log(res.data.data.cover)
        if (res.data.data.cover) {
          const {
            id,
            title,
            channel_id,
            content,
            cover: { type, images },
          } = res.data.data
          // 文章数据
          const article = {
            id,
            title,
            channel_id,
            content,
            type,
            images,
          }
          const { images: imgs, ...formValue } = article
          // 动态设置表单数据
          console.log('is')
          console.log('formValue', formValue)
          form.setFieldsValue(formValue)

          // 格式化封面图片数据
          const imageList = imgs.map((item) => ({ url: item }))
          setFileList(imageList)
          setCount(+formValue.type)
          fileArr.current = imageList
        }
      } catch {}
    }
    console.log(id)
    if (id) {
      getArticleList(id)
    }
  }, [dispatch, id, form])

  /**
   * 上传图片 或者删除已上传图片 都会触发此回调
   * @param info：{file:当前上传图像对象，fileList:最新上传图片列表}
   * @returns
   */
  const onUploadChange: UploadProps['onChange'] = ({
    file,
    fileList,
  }: UploadChangeParam<UploadFile>) => {
    console.log(file, fileList)
    const _fileList = fileList.map((item) => {
      // 1.处理正在上传的图片
      if (item.response) {
        return {
          url: item.response.data.url,
        }
      }
      // 2.处理已经上传的图片
      return item
    })
    console.log(_fileList)
    // 备份数据
    fileArr.current = _fileList
    setFileList(_fileList)
  }
  // 修改上传图片最大数量
  const changeMaxCount = (e: RadioChangeEvent) => {
    console.log(e.target.value)
    setCount(e.target.value)
    // 点击切换上传图片列表
    /**
     * 1. 切换单图：没有图片=》 [] | 已经上传了图片 1 张 只显示一张
     * 2. 切换三图：使用备份数据覆盖
     */
    if (e.target.value === 1) {
      const bk = fileArr.current[0]
      setFileList(bk ? [bk] : [])
    }
    if (e.target.value === 3) {
      setFileList(fileArr.current)
    }
  }
  //
  const pubArticle = async (data: Article, idDraft: boolean, id?: string) => {
    // console.log(data)
    const { type, ...sxd } = data
    // 判断选择图片的type 和以上传图片的数量对比
    console.log(type)
    if (type === undefined) return
    if (+type !== fileList.length) {
      return message.error('请传入对应数量的图片')
    }
    // 组装后台发布文章的参数
    const formData = {
      ...sxd,
      cover: {
        type,
        images: fileList.map((item) => item.url),
      },
    }
    console.log('发布文章参数', formData)
    try {
      if (id) {
        await dispatch(eidArticle({ id, draft: idDraft, formData }))
        message.success(idDraft ? '文章存入草稿成功' : '编辑文章成功')
        navigate('/article')
      } else {
        await dispatch(publishArticle({ draft: idDraft, formData }))
        message.success(idDraft ? '文章存入草稿成功' : '发布文章成功')
        navigate('/article')
      }
    } catch (error) {}
  }
  // 发布文章
  const confirmArticle = (data: Article) => {
    if (id) {
      pubArticle(data, false, id)
    } else {
      pubArticle(data, false)
    }
  }

  // 发布文章为草稿
  // 获取表单实例
  //
  const saveDraft = async () => {
    try {
      const formData = await form.validateFields()
      // 表单校验通过
      console.log(formData)
      if (id) {
        await pubArticle(formData, false, id)
      } else {
        pubArticle(formData, true)
      }
    } catch (error) {
      // 校验失败
      console.log(error)
    }
  }
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>发布文章</Breadcrumb.Item>
          </Breadcrumb>
        }>
        <Form
          form={form}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1 }}
          onFinish={confirmArticle}>
          {/* 文章标题 */}
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}>
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          {/* 文章频道 */}
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}>
            <Channel width={400} />
          </Form.Item>
          {/* 文章封面 */}
          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={changeMaxCount}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
                {/* <Radio value={-1}>自动</Radio> */}
              </Radio.Group>
            </Form.Item>
            {/* Upload 组件说明： */}
            {/* count > 0 才渲染 */}
            {count > 0 && (
              <Upload
                className="avatar-uploader"
                // 接口地址
                // 注意：Upload 再上传图片时，默认不会执行 axios 的请求，所以，此处需要手动设置完整接口地址
                action="http://geek.itheima.net/v1_0/upload"
                // 发到后台的文件参数名
                // 必须指定，根据接口文档的说明，需要设置为 image
                name="image"
                // 上传组件展示方式
                listType="picture-card"
                // 展示已上传图片列表
                showUploadList
                // 控制最大上传数量
                maxCount={count}
                // 多选
                multiple={count > 1}
                // 已经上传的文件列表，设置该属性后组件变为 受控
                fileList={fileList}
                // 上传文件改变时的回调
                onChange={onUploadChange}>
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          {/* 文章内容 */}
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}>
            {/* 富文本编辑器 */}
            <ReactQuill className="publish-quill" />
          </Form.Item>
          {/* 表单提交按钮 */}
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                发布文章
              </Button>
              <Button size="large" onClick={saveDraft}>
                存入草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish
